package com.xing.lei.happy.logic;

import com.google.common.collect.Maps;
import com.xing.lei.happy.dao.BaseService;
import com.xing.lei.happy.dao.Column;
import com.xing.lei.happy.dao.Table;
import com.xing.lei.happy.utils.DataSourceUtil;
import com.xing.lei.happy.utils.ExcelTools;
import com.xing.lei.happy.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ExcelToolsLogic {

    public void export(HttpServletResponse response, String entityName) throws UnsupportedEncodingException {
        String fileName = "批量导入实体属性-基本信息.xlsx";
        response.setContentType("application/excel");
        response.setHeader("Content-disposition",
                "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8") + ";filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
        String[] titles = {"实体表名", "属性中文名", "属性英文名", "是否标识", "排序号", "数据库字段类型", "长度", "精度", "是否可空","默认值","值域"};
        Map<String, Integer> pos = Maps.newHashMap();
        for (int i = 0; i < titles.length; i++) {
            pos.put(StringUtils.lowerCase(titles[i]), i);
        }
        List<Map<String, Object>> data = gateTableColumnData(entityName);
        ExcelTools.export(response, "实体属性导入", titles, pos, data);
    }

    private List<Map<String, Object>> gateTableColumnData(String entityName){
        List<Map<String, Object>> list =  new ArrayList<>();
        String[] entityNames = entityName.split("\\W");
        for (String entity : entityNames) {
            Map commentsNap = Maps.newHashMap();
            Map colsNap = Maps.newHashMap();
            try {
              //  Map params = Maps.newHashMap();
              //  params.put("table_name", entity.toUpperCase());
                List<Map<String, Object>>  tableComments = BaseService.getTableData(BaseService.getDataSource(),"user_col_comments"," table_name = '" + entity.toUpperCase() + "'");
               // List<Map> tableComments = commonService.selectByParam("user_col_comments", params);
                if (tableComments != null && tableComments.size() > 0) {
                    for (Map comment : tableComments) {
                        commentsNap.put(StringUtils.toString(comment.get("columnName")).toUpperCase(), comment.get("comments"));
                    }
                }
                List<Map<String, Object>>  tableCols = BaseService.getTableData(BaseService.getDataSource(),"user_tab_cols"," table_name = '" + entity.toUpperCase() + "'");
                //List<Map> tableCols = commonService.selectByParam("user_tab_cols", params);
                if (tableCols != null && tableCols.size() > 0) {
                    for (Map col : tableCols) {
                        colsNap.put(StringUtils.toString(col.get("columnName")).toUpperCase(), col.get("dataType"));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Map<String, Column> columns = BaseService.getTable().getColumns( entity);
            for (Map.Entry<String, Column> entry : columns.entrySet()) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("实体表名", entity.toUpperCase());
                map.put("属性中文名", commentsNap.get(entry.getKey().toUpperCase()));
                map.put("属性英文名", entry.getKey().toUpperCase());    // 数据库字段名
                if (entry.getValue().isPrimaryKey()) {
                    map.put("是否标识", "是");
                } else {
                    map.put("是否标识", "否");
                }
                map.put("排序号", "");
                map.put("长度", entry.getValue().getSize());
                String data_type = String.valueOf(colsNap.get(entry.getKey().toUpperCase()));
                switch (data_type) {
                    case "NUMBER":
                        data_type = "Number";
                        break;
                    case "VARCHAR":
                        data_type = "Variable characters";
                        break;
                    case "VARCHAR2":
                        data_type = "Variable characters";
                        break;
                    case "DATE":
                        data_type = "Date";
                        map.put("长度", "");
                        break;
                    case "TIMESTAMP":
                        data_type = "Date&Time";
                        map.put("长度", "");
                        break;
                    case "CLOB":
                        data_type = "CLOB";
                        break;
                    case "BLOB":
                        data_type = "BLOB";
                        break;
                    case "LONG":     // 数据库字段类型为LONG，实际类型为NUMBER
                        data_type = "Number";
                        break;
                    case "Binary":
                        data_type = "Binary";
                        break;
                    case "Short":
                        data_type = "Short Interger";
                        break;
                    case "INT":
                        data_type = "Integer";
                        break;
                    default:
                        data_type = "Variable characters";
                        break;
                }
                if (entry.getValue().isPrimaryKey()) {
                    map.put("数据库字段类型", "Identifier");
                } else {
                    map.put("数据库字段类型", data_type);
                }
                if ("LRRQ".equals(entry.getKey().toUpperCase()) || "XGRQ".equals(entry.getKey().toUpperCase())) {
                    map.put("数据库字段类型", "Date&Time");
                }
                if(entry.getValue().getDecimalDigits() > 0){
                    map.put("精度", entry.getValue().getDecimalDigits());
                }else {
                    map.put("精度", "");
                }
                if (entry.getValue().getNullable() == 1) {
                    map.put("是否可空", "是");
                } else {
                    map.put("是否可空", "否");
                }
                map.put("默认值", "");
                map.put("值域", "");
                list.add(map);
            }
        }
        return list;
    }


}